﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Gtkj.CMS.Common
{
    public class AccessHelper
    {
        private readonly HttpRequest Request;
        private readonly HttpResponse Response;
        private readonly MD5Helper MD5;

        private readonly string Key;

        public AccessHelper()
            : this("A3b4@#85")
        {
        }

        public AccessHelper(string Key)
        {
            Request = HttpContext.Current.Request;
            Response = HttpContext.Current.Response;
            this.Key = Key;
        }

        public bool IsAuthed
        {
            get
            {
                int? userId = UserId;
                string hash = Hash;
                if (userId == null || hash == null)
                {
                    return false;
                }
                return CheckVal(userId ?? default(int), hash);
            }
        }

        public int? UserId
        {
            set
            {
                if (value == null)
                {
                    var cookie = Response.Cookies["EPGUID"];
                    cookie.Expires = DateTime.Now.AddMinutes(-1);
                    Response.Cookies.Set(cookie);
                    cookie = Response.Cookies["EPGVAL"];
                    cookie.Expires = DateTime.Now.AddMinutes(-1);
                    Response.Cookies.Set(cookie);
                }
                else
                {
                    Response.Cookies.Add(new HttpCookie("EPGUID")
                    {
                        Path = "/",
                        Value = value.ToString()
                    });
                    Response.Cookies.Add(new HttpCookie("EPGVAL")
                    {
                        Path = "/",
                        Value = ComputeHash(value ?? default(int))
                    });
                }
            }
            get
            {
                var userId = Request.Cookies["EPGUID"];
                if (userId == null)
                {
                    return null;
                }
                try
                {
                    return int.Parse(userId.Value);
                }
                catch
                {
                    return null;
                }
            }
        }

        public string Hash
        {
            get
            {
                var hash = Request.Cookies["EPGVAL"];
                if (hash == null)
                {
                    return null;
                }
                return hash.Value;
            }
        }

        public bool CheckVal(int UserId, string hash)
        {
            return hash.ToLower() == ComputeHash(UserId);
        }

        public string ComputeHash(int UserId)
        {
            return MD5Helper.Encrypt(Key + "AbCdd&^%" + UserId.ToString() + "&啦啦你妹&@");
        }
    }
}